<template>
  <view class="production-workspace">
    <!-- 生产员工工作台 -->
    <view v-if="!isManager" class="employee-workspace">
      <!-- 生产计划中心 -->
      <view class="plan-center bg-white margin-bottom radius">
        <view class="section-header padding flex justify-between align-center">
          <text class="text-lg text-bold">生产计划中心</text>
          <view class="header-right flex align-center">
            <view class="tab-switch">
              <view
                v-for="tab in planTabs"
                :key="tab.key"
                :class="[
                  'tab-item',
                  currentPlanTab === tab.key ? 'active' : '',
                ]"
                @tap="switchPlanTab(tab.key)"
              >
                {{ tab.label }}
              </view>
            </view>
            <button
              class="more-btn cu-btn line-blue sm margin-left-sm"
              @tap="goToPlanList"
            >
              更多
            </button>
          </view>
        </view>

        <!-- 全部计划 -->
        <view v-if="currentPlanTab === 'available'" class="available-plans">
          <view
            v-if="availablePlans.length === 0"
            class="empty-state padding text-center text-gray"
          >
            <text class="cuIcon-calendar text-xxl"></text>
            <view class="margin-top-sm">暂无计划</view>
          </view>
          <scroll-view v-else scroll-y class="plan-scroll-container">
            <view
              v-for="plan in availablePlans"
              :key="plan.id"
              class="plan-item padding-sm border-bottom"
            >
              <view class="flex justify-between align-center margin-bottom-sm">
                <view class="flex-sub">
                  <view class="text-bold">{{ plan.planName }}</view>
                  <view class="text-sm text-gray margin-top-xs">
                    订单号：{{ plan.orderNo }} | 数量：{{ plan.planQuantity }}
                  </view>
                  <view class="text-sm text-gray margin-top-xs">
                    计划时间：{{ plan.planStartDate }} - {{ plan.planEndDate }}
                  </view>
                </view>
              </view>
              <!-- 任务统计信息 -->
              <view class="task-stats-container margin-top-sm">
                <view class="grid col-3 gap-sm">
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-blue">{{
                      plan.totalTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">总任务</view>
                  </view>
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-orange">{{
                      plan.pendingTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">待处理</view>
                  </view>
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-green">{{
                      plan.completedTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">已完成</view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 我的计划 -->
        <view v-else-if="currentPlanTab === 'my'" class="my-plans">
          <view
            v-if="myPlans.length === 0"
            class="empty-state padding text-center text-gray"
          >
            <text class="cuIcon-calendar text-xxl"></text>
            <view class="margin-top-sm">暂无进行中计划</view>
          </view>
          <scroll-view v-else scroll-y class="plan-scroll-container">
            <view
              v-for="plan in myPlans"
              :key="plan.id"
              class="plan-item padding-sm border-bottom"
            >
              <view class="flex justify-between align-center margin-bottom-sm">
                <view class="flex-sub">
                  <view class="text-bold">{{ plan.planName }}</view>
                  <view class="text-sm text-gray margin-top-xs">
                    订单号：{{ plan.orderNo }} | 数量：{{ plan.planQuantity }}
                  </view>
                  <view class="text-sm text-gray margin-top-xs">
                    计划时间：{{ plan.planStartDate }} - {{ plan.planEndDate }}
                  </view>
                </view>
              </view>
              <!-- 任务统计信息 -->
              <view class="task-stats-container margin-top-sm">
                <view class="grid col-3 gap-sm">
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-blue">{{
                      plan.totalTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">总任务</view>
                  </view>
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-orange">{{
                      plan.pendingTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">待处理</view>
                  </view>
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-green">{{
                      plan.completedTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">已完成</view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 历史计划 -->
        <view v-else-if="currentPlanTab === 'history'" class="history-plans">
          <view
            v-if="historyPlans.length === 0"
            class="empty-state padding text-center text-gray"
          >
            <text class="cuIcon-time text-xxl"></text>
            <view class="margin-top-sm">暂无历史计划</view>
          </view>
          <scroll-view v-else scroll-y class="plan-scroll-container">
            <view
              v-for="plan in historyPlans"
              :key="plan.id"
              class="plan-item padding-sm border-bottom"
            >
              <view class="flex justify-between align-center margin-bottom-sm">
                <view class="flex-sub">
                  <view class="text-bold">{{ plan.planName }}</view>
                  <view class="text-sm text-gray margin-top-xs">
                    订单号：{{ plan.orderNo }} | 数量：{{ plan.planQuantity }}
                  </view>
                  <view class="text-sm text-gray margin-top-xs">
                    计划时间：{{ plan.planStartDate }} - {{ plan.planEndDate }}
                  </view>
                </view>
              </view>
              <!-- 任务统计信息 -->
              <view class="task-stats-container margin-top-sm">
                <view class="grid col-3 gap-sm">
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-blue">{{
                      plan.totalTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">总任务</view>
                  </view>
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-orange">{{
                      plan.pendingTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">待处理</view>
                  </view>
                  <view
                    class="stat-item text-center padding-xs radius bg-gray-light"
                  >
                    <view class="stat-value text-lg text-bold text-green">{{
                      plan.completedTasks || 0
                    }}</view>
                    <view class="stat-label text-xs text-gray">已完成</view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>

      <!-- 通知中心 -->
      <view class="notification-center bg-white margin-bottom radius">
        <view class="section-header padding flex justify-between align-center">
          <text class="text-lg text-bold">通知中心</text>
          <button
            class="more-btn cu-btn line-blue sm"
            @tap="goToNotificationList"
          >
            更多
          </button>
        </view>
        <view
          v-if="notifications.length === 0"
          class="empty-state padding text-center text-gray"
        >
          <text class="cuIcon-notification text-xxl"></text>
          <view class="margin-top-sm">暂无新通知</view>
        </view>
        <view v-else class="notification-list">
          <view
            v-for="notification in notifications"
            :key="notification.id"
            :class="[
              'notification-item padding-sm border-bottom',
              notification.readFlag === '0' ? 'unread' : '',
            ]"
            @tap="handleNotificationTap(notification)"
          >
            <view class="flex align-start">
              <view
                :class="[
                  'notification-icon',
                  'margin-right-sm',
                  getNotificationIconClass(notification.priority),
                ]"
              ></view>
              <view class="flex-sub">
                <view class="text-bold">{{ notification.titile }}</view>
                <view class="text-sm text-gray margin-top-xs line-clamp-2">
                  {{ getPlainTextContent(notification.msgContent) }}
                </view>
                <view class="text-xs text-gray margin-top-xs">
                  {{ formatNotificationTime(notification.sendTime) }}
                </view>
              </view>
              <view
                v-if="notification.readFlag === '0'"
                class="unread-dot"
              ></view>
            </view>
          </view>
        </view>
      </view>

      <!-- 异常上报 -->
      <!-- <view class="exception-report bg-white margin-bottom radius">
        <view class="section-header padding">
          <text class="text-lg text-bold">异常上报</text>
        </view>
        <view class="report-actions padding">
          <view class="grid col-3 gap-sm">
            <view
              v-for="reportType in reportTypes"
              :key="reportType.type"
              class="report-btn text-center padding-sm radius bg-gray-light"
              @tap="reportException(reportType.type)"
            >
              <view
                :class="reportType.icon"
                :style="{ color: reportType.color }"
                class="text-xl"
              ></view>
              <view class="text-sm margin-top-xs">{{ reportType.label }}</view>
            </view>
          </view>
        </view>
      </view> -->
    </view>

    <!-- 生产管理员工作台 -->
    <view v-else class="admin-workspace">
      <!-- 计划管理中心 -->
      <view class="plan-management bg-white margin-bottom radius">
        <view class="section-header padding">
          <text class="text-lg text-bold">计划管理</text>
        </view>
        <view class="plan-actions padding">
          <view class="grid col-2 gap-sm">
            <view
              v-for="planAction in planActions"
              :key="planAction.type"
              class="plan-btn bg-white padding radius shadow flex align-center"
              @tap="navigateTo(planAction.path)"
            >
              <view
                :class="planAction.icon"
                :style="{ color: planAction.color }"
                class="text-lg margin-right-sm"
              ></view>
              <view>
                <view class="text-bold">{{ planAction.name }}</view>
                <view class="text-sm text-gray">{{ planAction.desc }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 审批中心 -->
      <view class="approval-center bg-white margin-bottom radius">
        <view class="section-header padding">
          <text class="text-lg text-bold">审批中心</text>
        </view>
        <view
          v-if="pendingApprovals.length === 0"
          class="empty-state padding text-center text-gray"
        >
          <text class="cuIcon-check text-xxl"></text>
          <view class="margin-top-sm">暂无待审批事项</view>
        </view>
        <view v-else class="approval-list">
          <view
            v-for="approval in pendingApprovals"
            :key="approval.id"
            class="approval-item padding-sm border-bottom"
          >
            <view class="flex justify-between align-center margin-bottom-sm">
              <view class="flex-sub">
                <view class="text-bold">{{ approval.title }}</view>
                <view class="text-sm text-gray margin-top-xs">
                  申请人：{{ approval.applicant }} | {{ approval.time }}
                </view>
              </view>
              <view :class="approval.urgencyClass" class="urgency-badge">
                {{ approval.urgency }}
              </view>
            </view>
            <view class="approval-actions flex gap-sm">
              <button
                class="cu-btn bg-green sm"
                @tap="approveItem(approval.id)"
              >
                通过
              </button>
              <button class="cu-btn bg-red sm" @tap="rejectItem(approval.id)">
                驳回
              </button>
              <button
                class="cu-btn line-blue sm"
                @tap="viewApprovalDetail(approval.id)"
              >
                详情
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 实时监控 -->
      <view class="real-time-monitor bg-white radius">
        <view class="section-header padding">
          <text class="text-lg text-bold">实时监控</text>
        </view>
        <view class="monitor-stats padding">
          <view class="grid col-2 gap-sm">
            <view
              v-for="stat in monitorStats"
              :key="stat.key"
              class="stat-card bg-gray-light padding-sm radius text-center"
            >
              <view :class="stat.class" class="stat-value text-lg text-bold">{{
                stat.value
              }}</view>
              <view class="stat-label text-sm text-gray margin-top-xs">{{
                stat.label
              }}</view>
            </view>
          </view>
        </view>
        <view class="monitor-actions padding-top">
          <button
            class="cu-btn bg-blue block"
            @tap="navigateTo('/pages/mes/analytics/dashboard')"
          >
            查看详细监控
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import authService from "@/common/auth/authService.js";
import { productionPlan } from "@/api/mes/productionPlan.js";
import { announcement } from "@/api/sys/announcement.js";
import { USER_INFO } from "@/common/util/constants.js";

export default {
  name: "ProductionWorkspace",

  data() {
    return {
      currentPlanTab: "available",
      planTabs: [
        { key: "available", label: "全部" },
        { key: "my", label: "当前参与" },
        { key: "history", label: "历史" },
      ],
      availablePlans: [],
      myPlans: [],
      historyPlans: [],
      notifications: [],
      reportTypes: [
        {
          type: "production",
          label: "生产异常",
          icon: "cuIcon-warn",
          color: "#f5222d",
        },
        {
          type: "quality",
          label: "质量问题",
          icon: "cuIcon-close",
          color: "#fa8c16",
        },
        {
          type: "equipment",
          label: "设备故障",
          icon: "cuIcon-settings",
          color: "#722ed1",
        },
      ],
      statusActions: [],
      // 管理员数据
      planActions: [
        {
          type: "create",
          name: "创建计划",
          desc: "新建生产计划",
          icon: "cuIcon-add",
          color: "#1890ff",
          path: "/pages/mes/plan/create",
        },
        {
          type: "adjust",
          name: "调整计划",
          desc: "修改现有计划",
          icon: "cuIcon-edit",
          color: "#52c41a",
          path: "/pages/mes/plan/list",
        },
        {
          type: "template",
          name: "计划模板",
          desc: "管理计划模板",
          icon: "cuIcon-copy",
          color: "#fa8c16",
          path: "/pages/mes/system/template",
        },
        {
          type: "monitor",
          name: "计划监控",
          desc: "实时监控执行",
          icon: "cuIcon-time",
          color: "#722ed1",
          path: "/pages/mes/plan/monitor",
        },
      ],
      pendingApprovals: [],
      monitorStats: [],
    };
  },

  computed: {
    isManager() {
      const loginType = uni.getStorageSync("erp_login_type");
      return loginType == "admin";
    },
  },

  mounted() {
    this.initWorkspace();
  },

  onShow() {
    this.refreshData();
  },

  methods: {
    initWorkspace() {
      if (!this.isManager) {
        this.loadEmployeeData();
      } else {
        this.loadAdminData();
      }
    },

    // 员工数据加载
    loadEmployeeData() {
      this.loadAllPlans();
      this.loadMyPlans();
      this.loadHistoryPlans();
      this.loadNotifications();
      this.loadWorkStatusActions();
    },

    async loadAllPlans() {
      try {
        console.log("loadAllPlans");

        const userInfo = uni.getStorageSync(USER_INFO);
        console.log(userInfo);
        if (!userInfo || !userInfo.id) {
          console.warn("用户信息不完整，无法加载全部计划");
          return;
        }

        // 使用生产计划API获取全部计划
        const res = await productionPlan.list({
          pageNo: 1,
          pageSize: 10,
          // 不限制状态，显示所有计划
        });

        const response = res.data || res;
        if (response.success || response.code == 200) {
          const planData =
            response.result?.records || response.data || response.records || [];
          console.log("Plan data:", planData);

          // 为每个计划获取任务统计信息
          const plansWithStats = await Promise.all(
            planData.map(async (plan) => {
              const taskStats = await this.getTaskStatistics(plan.id);
              return {
                id: plan.id,
                planName: plan.planName || "生产计划",
                productInfo: plan.productInfo || "未知产品",
                planQuantity: plan.planQuantity || 0,
                planStartDate: this.formatDate(plan.planStartDate),
                planEndDate: this.formatDate(plan.planEndDate),
                priority: plan.priority || 2,
                orderNo: plan.orderNo,
                totalTasks: plan.totalTasks,
                pendingTasks: plan.pendingTasks,
                completedTasks: plan.completedTasks,
              };
            })
          );

          this.availablePlans = plansWithStats;

          console.log("Processed all plans:", this.availablePlans);
        }
      } catch (error) {
        console.error("加载全部计划失败:", error);
        uni.showToast({
          title: "加载计划失败",
          icon: "none",
        });
      }
    },

    // 获取计划的任务统计信息
    async getTaskStatistics(planId) {
      try {
        // 这里需要调用任务API获取统计信息
        // 假设有一个API可以获取计划下的任务统计
        const taskRes = await uni.request({
          url: `${this.$config.baseUrl}/mes/productionPlanTask/statistics`,
          method: "GET",
          data: { planId: planId },
          header: {
            "X-Access-Token": uni.getStorageSync("Access-Token"),
          },
        });

        if (taskRes.data && taskRes.data.success) {
          const stats = taskRes.data.result || {};
          return {
            total: stats.totalTasks || 0,
            pending: stats.pendingTasks || 0,
            completed: stats.completedTasks || 0,
          };
        }
      } catch (error) {
        console.error(`获取计划${planId}任务统计失败:`, error);
      }

      // 如果API调用失败，返回默认值
      return {
        total: 0,
        pending: 0,
        completed: 0,
      };
    },

    async loadMyPlans() {
      try {
        const userInfo = uni.getStorageSync(USER_INFO);
        if (!userInfo || !userInfo.id) {
          console.warn("用户信息不完整，无法加载当前参与计划");
          return;
        }

        // 使用新的API根据任务领取人获取参与的计划（状态为4：进行中）
        const response = await productionPlan.getPlansByTaskOwnership({
          employeeId: userInfo.id,
          planStatus: 4, // 进行中状态
          pageNo: 1,
          pageSize: 10,
        });

        const res = response.data || response;
        if (res.success || res.code == 200) {
          console.log("My plans response:", res);
          const planData = res.result?.records || res.data || res.records || [];
          console.log("My plan data:", planData);

          // 为每个计划获取任务统计信息
          const plansWithStats = await Promise.all(
            planData.map(async (plan) => {
              const taskStats = await this.getTaskStatistics(plan.id);
              return {
                id: plan.id,
                planName: plan.planName || "生产计划",
                productInfo: plan.productInfo || "未知产品",
                planQuantity: plan.planQuantity || 0,
                planStartDate: this.formatDate(plan.planStartDate),
                planEndDate: this.formatDate(plan.planEndDate),
                priority: plan.priority || 2,
                orderNo: plan.orderNo,
                totalTasks: plan.totalTasks,
                pendingTasks: plan.pendingTasks,
                completedTasks: plan.completedTasks,
              };
            })
          );

          this.myPlans = plansWithStats;

          console.log("Processed my plans:", this.myPlans);
        }
      } catch (error) {
        console.error("加载当前参与计划失败:", error);
        uni.showToast({
          title: "加载计划失败",
          icon: "none",
        });
      }
    },

    async loadHistoryPlans() {
      try {
        const userInfo = uni.getStorageSync(USER_INFO);
        if (!userInfo || !userInfo.id) {
          console.warn("用户信息不完整，无法加载历史计划");
          return;
        }

        // 使用新的API根据任务领取人获取参与的计划（状态为5：已完成）
        const response = await productionPlan.getPlansByTaskOwnership({
          employeeId: userInfo.id,
          planStatus: 5, // 已完成状态
          pageNo: 1,
          pageSize: 10,
        });

        const res = response.data || response;
        if (res.success || res.code == 200) {
          console.log("History plans response:", res);
          const planData = res.result?.records || res.data || res.records || [];
          console.log("History plan data:", planData);

          // 为每个计划获取任务统计信息
          const plansWithStats = await Promise.all(
            planData.map(async (plan) => {
              const taskStats = await this.getTaskStatistics(plan.id);
              return {
                id: plan.id,
                planName: plan.planName || "生产计划",
                productInfo: plan.productInfo || "未知产品",
                planQuantity: plan.planQuantity || 0,
                planStartDate: this.formatDate(plan.planStartDate),
                planEndDate: this.formatDate(plan.planEndDate),
                priority: plan.priority || 2,
                orderNo: plan.orderNo,
                totalTasks: plan.totalTasks,
                pendingTasks: plan.pendingTasks,
                completedTasks: plan.completedTasks,
              };
            })
          );

          this.historyPlans = plansWithStats;

          console.log("Processed history plans:", this.historyPlans);
        }
      } catch (error) {
        console.error("加载历史计划失败:", error);
        uni.showToast({
          title: "加载历史计划失败",
          icon: "none",
        });
      }
    },

    async loadNotifications() {
      try {
        const userInfo = uni.getStorageSync(USER_INFO);
        if (!userInfo || !userInfo.id) {
          console.warn("用户信息不完整，无法加载通知");
          return;
        }

        // 使用announcement API获取通知数据
        const res = await announcement.getMyAnnouncementSend({
          pageNo: 1,
          pageSize: 5, // 只显示最新的5条通知
        });

        const response = res.data || res;

        if (response && response.success) {
          const notificationData =
            response.result?.records || response.result || [];
          this.notifications = notificationData.map((item) => ({
            id: item.id,
            titile: item.titile,
            msgContent: item.msgContent,
            sendTime: item.sendTime,
            priority: item.priority,
            readFlag: item.readFlag,
            anntId: item.anntId,
          }));

          console.log("Loaded notifications:", this.notifications);
        } else {
          console.error("获取通知失败:", response?.message);
        }
      } catch (error) {
        console.error("加载通知失败:", error);
        // 如果API调用失败，显示空状态
        this.notifications = [];
      }
    },

    loadWorkStatusActions() {
      this.statusActions = [
        {
          type: "checkin",
          label: "上班打卡",
          icon: "cuIcon-check",
          active: false,
        },
        { type: "break", label: "休息", icon: "cuIcon-time", active: false },
        { type: "overtime", label: "加班", icon: "cuIcon-add", active: false },
        {
          type: "checkout",
          label: "下班打卡",
          icon: "cuIcon-close",
          active: false,
        },
      ];
    },

    // 管理员数据加载
    loadAdminData() {
      this.loadPendingApprovals();
      this.loadMonitorStats();
    },

    loadPendingApprovals() {
      // 模拟API调用
      setTimeout(() => {
        const approvals = [
          {
            id: 1,
            title: "生产计划变更申请",
            applicant: "张三",
            time: "30分钟前",
            urgency: "紧急",
          },
          {
            id: 2,
            title: "设备维修申请",
            applicant: "李四",
            time: "1小时前",
            urgency: "普通",
          },
        ];

        // 预计算紧急程度样式
        this.pendingApprovals = approvals.map((approval) => ({
          ...approval,
          urgencyClass: this.calculateUrgencyClass(approval.urgency),
        }));
      }, 500);
    },

    loadMonitorStats() {
      this.monitorStats = [
        { key: "online", label: "在线员工", value: 28, class: "text-green" },
        { key: "tasks", label: "进行中任务", value: 15, class: "text-blue" },
        {
          key: "efficiency",
          label: "生产效率",
          value: "92%",
          class: "text-orange",
        },
        { key: "alerts", label: "异常告警", value: 2, class: "text-red" },
      ];
    },

    // 样式计算方法（避免在模板中调用）
    calculatePlanStatusClass(status) {
      const statusMap = {
        0: "text-gray", // 待审核
        1: "text-blue", // 已审核
        2: "text-orange", // 已下发
        3: "text-orange", // 已领取
        4: "text-blue", // 生产中
        5: "text-green", // 已完成
        6: "text-red", // 已取消
      };
      return statusMap[status] || "text-gray";
    },

    calculatePlanStatusText(status) {
      const textMap = {
        0: "待审核",
        1: "已审核",
        2: "已下发",
        3: "已领取",
        4: "生产中",
        5: "已完成",
        6: "已取消",
      };
      return textMap[status] || "未知";
    },

    // 计算进度百分比
    calculateProgress(actualQuantity, planQuantity) {
      if (!planQuantity || planQuantity === 0) return 0;
      return Math.round((actualQuantity / planQuantity) * 100);
    },

    // 格式化日期
    formatDate(dateTime) {
      if (!dateTime) return "";
      const date = new Date(dateTime);
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return "";
      const date = new Date(dateTime);
      return `${date.getMonth() + 1}/${date.getDate()} ${String(
        date.getHours()
      ).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
    },

    calculateUrgencyClass(urgency) {
      const urgencyMap = {
        紧急: "text-red",
        重要: "text-orange",
        普通: "text-blue",
      };
      return urgencyMap[urgency] || "text-gray";
    },

    // 事件处理方法
    switchPlanTab(tab) {
      this.currentPlanTab = tab;
    },

    completePlan(planId) {
      uni.showModal({
        title: "确认完成",
        content: "确定要完成这个生产计划吗？",
        success: async (res) => {
          if (res.confirm) {
            try {
              const userInfo = uni.getStorageSync(USER_INFO);
              if (!userInfo || !userInfo.id) {
                uni.showToast({ title: "用户信息异常", icon: "none" });
                return;
              }

              uni.showLoading({ title: "提交中..." });

              const response = await productionPlan.completePlan({
                planId: planId,
                employeeId: userInfo.id,
                completedQuantity: 0,
                actualHours: 0,
                remark: "",
              });

              if (response.success) {
                uni.showToast({ title: "计划已完成", icon: "success" });
                this.loadMyPlans();
                this.loadHistoryPlans();
              } else {
                uni.showToast({
                  title: response.message || "完成失败",
                  icon: "none",
                });
              }
            } catch (error) {
              console.error("完成计划失败:", error);
              uni.showToast({ title: "完成计划失败", icon: "none" });
            } finally {
              uni.hideLoading();
            }
          }
        },
      });
    },

    viewPlanDetail(planId) {
      uni.navigateTo({
        url: `/pages/mes/plan/detail?id=${planId}`,
      });
    },

    // 处理通知点击事件
    async handleNotificationTap(notification) {
      try {
        // 如果未读，标记为已读
        if (notification.readFlag === "0") {
          await this.markNotificationAsRead(notification.id);
        }

        // 直接跳转到消息详情页面
        uni.navigateTo({
          url: `/pages/system/notification/detail?id=${
            notification.anntId
          }&title=${encodeURIComponent(
            notification.titile
          )}&content=${encodeURIComponent(
            notification.msgContent
          )}&time=${encodeURIComponent(notification.sendTime)}&priority=${
            notification.priority
          }`,
          fail: (error) => {
            console.error("跳转消息详情页面失败:", error);
            uni.showToast({
              title: "页面跳转失败",
              icon: "none",
            });
          },
        });
      } catch (error) {
        console.error("处理通知点击失败:", error);
      }
    },

    // 标记通知为已读
    async markNotificationAsRead(notificationId) {
      try {
        const response = await announcement.markAsRead({
          anntId: notificationId,
          readFlag: "1",
        });

        if (response && response.success) {
          // 更新本地状态
          const notification = this.notifications.find(
            (n) => n.id === notificationId
          );
          if (notification) {
            notification.readFlag = "1";
          }
        }
      } catch (error) {
        console.error("标记通知已读失败:", error);
      }
    },

    // 显示通知详情
    showNotificationDetail(notification) {
      // 使用自定义模态框替代系统默认模态框
      this.showCustomNotificationModal(notification);
    },

    // 显示自定义通知模态框
    showCustomNotificationModal(notification) {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];

      // 创建自定义模态框页面
      uni.navigateTo({
        url: `/pages/system/notification/detail?id=${
          notification.anntId
        }&title=${encodeURIComponent(
          notification.titile
        )}&content=${encodeURIComponent(
          notification.msgContent
        )}&time=${encodeURIComponent(notification.sendTime)}&priority=${
          notification.priority
        }`,
        fail: () => {
          // 如果页面不存在，回退到系统模态框
          uni.showModal({
            title: notification.titile,
            content: this.getPlainTextContent(notification.msgContent),
            showCancel: false,
            confirmText: "知道了",
          });
        },
      });
    },

    // 获取通知图标样式类
    getNotificationIconClass(priority) {
      const iconMap = {
        H: "cuIcon-warn text-red", // 高优先级
        M: "cuIcon-notification text-orange", // 中优先级
        L: "cuIcon-info text-blue", // 低优先级
      };
      return iconMap[priority] || "cuIcon-notification text-blue";
    },

    // 从HTML内容中提取纯文本
    getPlainTextContent(htmlContent) {
      if (!htmlContent) return "";
      // 移除HTML标签，只保留文本内容
      return htmlContent
        .replace(/<[^>]*>/g, "")
        .replace(/\s+/g, " ")
        .trim();
    },

    // 格式化通知时间
    formatNotificationTime(dateTime) {
      if (!dateTime) return "";

      const now = new Date();
      const notificationDate = new Date(dateTime);
      const diffMs = now - notificationDate;
      const diffMins = Math.floor(diffMs / (1000 * 60));
      const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
      const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

      if (diffMins < 1) return "刚刚";
      if (diffMins < 60) return `${diffMins}分钟前`;
      if (diffHours < 24) return `${diffHours}小时前`;
      if (diffDays < 7) return `${diffDays}天前`;

      // 超过7天显示具体日期
      return `${notificationDate.getMonth() + 1}/${notificationDate.getDate()}`;
    },

    // 跳转到通知列表页面
    goToNotificationList() {
      uni.navigateTo({
        url: "/pages/system/notification/list",
      });
    },

    reportException(type) {
      uni.navigateTo({
        url: `/pages/mes/exception/report?type=${type}`,
      });
    },

    changeWorkStatus(type) {
      const action = this.statusActions.find((a) => a.type === type);
      if (action) {
        action.active = !action.active;
        uni.showToast({
          title: `${action.label}${action.active ? "成功" : "取消"}`,
          icon: "success",
        });
      }
    },

    approveItem(approvalId) {
      uni.showModal({
        title: "确认审批",
        content: "确定要通过这个申请吗？",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: "处理中..." });
            setTimeout(() => {
              uni.hideLoading();
              uni.showToast({ title: "审批通过", icon: "success" });
              this.loadPendingApprovals();
            }, 1000);
          }
        },
      });
    },

    rejectItem(approvalId) {
      uni.showModal({
        title: "确认驳回",
        content: "确定要驳回这个申请吗？",
        success: (res) => {
          if (res.confirm) {
            uni.showLoading({ title: "处理中..." });
            setTimeout(() => {
              uni.hideLoading();
              uni.showToast({ title: "已驳回", icon: "success" });
              this.loadPendingApprovals();
            }, 1000);
          }
        },
      });
    },

    viewApprovalDetail(approvalId) {
      uni.navigateTo({
        url: `/pages/mes/approval/detail?id=${approvalId}`,
      });
    },

    navigateTo(path) {
      if (path) {
        uni.navigateTo({
          url: path,
          fail: () => {
            uni.showToast({
              title: "页面暂未开放",
              icon: "none",
            });
          },
        });
      }
    },

    // 跳转到生产计划列表页面
    goToPlanList() {
      uni.navigateTo({
        url: "/pages/production/plan/list",
        fail: () => {
          uni.showToast({
            title: "页面跳转失败",
            icon: "none",
          });
        },
      });
    },

    refreshData() {
      if (!this.isManager) {
        this.loadEmployeeData();
      } else {
        this.loadAdminData();
      }
    },

    // 映射计划状态
    mapPlanStatus(backendStatus) {
      const statusMap = {
        0: "pending", // 待分配
        1: "claimed", // 已领取
        2: "in-progress", // 进行中
        3: "paused", // 已暂停
        4: "completed", // 已完成
        5: "cancelled", // 已取消
      };
      return statusMap[backendStatus] || "unknown";
    },

    // 映射优先级
    mapPriority(backendPriority) {
      const priorityMap = {
        1: "low",
        2: "medium",
        3: "high",
        4: "urgent",
      };
      return priorityMap[backendPriority] || "medium";
    },
  },
};
</script>

<style lang="scss" scoped>
.production-workspace {
  padding: 0 24rpx;
}

.section-header {
  border-bottom: 1rpx solid #f0f0f0;
}

.tab-switch {
  display: flex;
  background-color: #f5f5f5;
  border-radius: 6rpx;
  padding: 4rpx;

  .tab-item {
    padding: 8rpx 16rpx;
    font-size: 24rpx;
    border-radius: 4rpx;
    color: #666;

    &.active {
      background-color: white;
      color: #1890ff;
      font-weight: bold;
    }
  }
}

// 通知中心样式
.notification-center {
  .notification-list {
    max-height: 400rpx;
    overflow-y: auto;
  }

  .notification-item {
    position: relative;
    transition: background-color 0.3s;

    &.unread {
      background-color: #f6ffed;
      border-left: 4rpx solid #52c41a;
    }

    &:active {
      background-color: #f5f5f5;
    }

    .notification-icon {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background-color: #f0f0f0;
      font-size: 20rpx;
    }

    .unread-dot {
      width: 12rpx;
      height: 12rpx;
      background-color: #ff4d4f;
      border-radius: 50%;
      position: absolute;
      top: 20rpx;
      right: 20rpx;
    }

    .line-clamp-2 {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      line-height: 1.4;
      max-height: 2.8em;
    }
  }
}

.task-item {
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .task-status {
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
    font-size: 24rpx;
    background-color: #f0f0f0;
  }

  .task-actions {
    margin-top: 16rpx;
  }
}

.notification-item {
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  &.unread {
    background-color: #f6ffed;
  }

  .notification-icon {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
  }
}

.report-btn {
  border: 1rpx solid #e8e8e8;

  &:active {
    background-color: #f0f0f0;
  }
}

.status-btn {
  border-radius: 8rpx;
  border: 1rpx solid #e8e8e8;

  &.active {
    background-color: #e6f7ff;
    border-color: #1890ff;
    color: #1890ff;
  }

  &:active {
    background-color: #f0f0f0;
  }
}

.plan-btn,
.admin-action-btn {
  border: 1rpx solid #e8e8e8;

  &:active {
    background-color: #f0f0f0;
  }
}

.approval-item {
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }

  .urgency-badge {
    padding: 4rpx 12rpx;
    border-radius: 12rpx;
    font-size: 24rpx;
    background-color: #f0f0f0;
  }

  .approval-actions {
    margin-top: 16rpx;
  }
}

.stat-card {
  border: 1rpx solid #e8e8e8;

  .stat-value {
    font-size: 32rpx;
  }
}

.empty-state {
  color: #999;

  .cuIcon {
    display: block;
    margin: 0 auto 16rpx;
  }
}

.task-scroll-container {
  max-height: 400rpx;
  overflow-y: auto;
}
</style>
